package framework.shiro;

import java.util.HashSet;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.ExpiredCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.sunny.dao.IPermissionDao;
import com.sunny.dao.IRoleDao;
import com.sunny.dao.IUserDao;
import com.sunny.model.User;
import com.sunny.query.UserQuery;

import framework.common.UserSecurity;

public class UserRealm extends AuthorizingRealm {

	@Resource
	private IUserDao userDao;
	@Resource
	private IRoleDao roleDao;
	@Resource
	private IPermissionDao permissionDao;

	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		List<String> selectRoleNameList = roleDao.selectRoleNameList(username);
		List<String> permissionList = permissionDao.selectPermissionList(username);
		authorizationInfo.setRoles(new HashSet<String>(selectRoleNameList));
		authorizationInfo.setStringPermissions(new HashSet<String>(permissionList));
		return authorizationInfo;
	}

	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		UserQuery uq = new UserQuery();
		uq.setUserId(username);
		User user = userDao.selectOne(uq);
		if (user == null) {
			throw new UnknownAccountException();// 没找到帐号
		}
		// 1:正常，2：冻结，3：删除，4：锁定
		if (user.getStatus() == 2) {
			throw new DisabledAccountException(); // 帐号冻结
		}
		if (user.getStatus() == 3) {
			throw new ExpiredCredentialsException(); // 帐号删除
		}
		if (user.getStatus() == 4) {
			throw new LockedAccountException(); // 帐号锁定
		}

		return new SimpleAuthenticationInfo(user.getUserId(), // 用户名
				user.getPassword(), // 密码
				ByteSource.Util.bytes(UserSecurity.getCredentialsSalt(user.getUserId())), // salt=username+salt
				getName() // realm name
		);
	}
	
	
}